<script setup lang="ts">
import Motion from "./utils/motion";
import { useRouter } from "vue-router";
import { message } from "@/utils/message";
import { loginRules } from "./utils/rule";
import { useNav } from "@/layout/hooks/useNav";
import type { FormInstance } from "element-plus";
import { useLayout } from "@/layout/hooks/useLayout";
import { useUserStoreHook } from "@/store/modules/user";
import { initRouter, getTopMenu } from "@/router/utils";
import { bg, avatar, illustration } from "./utils/static";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { ref, reactive, toRaw, onMounted, onBeforeUnmount } from "vue";
import { useDataThemeChange } from "@/layout/hooks/useDataThemeChange";
import { login, register } from "@/api/inspector";
import { useInspectorStoreHook } from "@/store/modules/inspector";
import { addGridProvince, listProvinces } from "@/api/gridProvince";
import { getGridCityByProvinceId } from "@/api/gridCity";
import TypeIt from "@/components/ReTypeit";
import dayIcon from "@/assets/svg/day.svg?component";
import darkIcon from "@/assets/svg/dark.svg?component";
import Lock from "@iconify-icons/ri/lock-fill";
import User from "@iconify-icons/ri/user-3-fill";
import { use } from "echarts/types/src/extension.js";
import { number } from "echarts";
import { provinceAndCityData, regionData } from "element-china-area-data";
import cities from "@/views/login/data/cities.js";

defineOptions({
  name: "Login"
});
const router = useRouter();
const loading = ref(false);
const ruleFormRef = ref<FormInstance>();
const ruleFormRegisterRef = ref<FormInstance>();
const currentPage = ref(0);
const checked = ref(false);

const { initStorage } = useLayout();
initStorage();

const repeatPasswordRule = [
  {
    validator: (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入确认密码"));
      } else if (ruleFormRegister.registerPassword !== value) {
        callback(new Error("两次输入的密码不一致，请重新输入"));
      } else {
        callback();
      }
    },
    trigger: "blur"
  }
];

const { dataTheme, overallStyle, dataThemeChange } = useDataThemeChange();
dataThemeChange(overallStyle.value);
const { title } = useNav();

const ruleFormRegister = reactive({
  insId: 0,
  registerPassword: "",
  insTel: "",
  insAddress: "",
  insState: 1,
  insName: "",
  repeatPassword: ""
});

const ruleForm = reactive({
  username: 1,
  password: "ins123456"
});

const onLogin = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      loading.value = true;
      useInspectorStoreHook()
        .loginByInsIdByPass({
          insId: ruleForm.username,
          insPassword: ruleForm.password
        })
        .then(res => {
          if (res === 200) {
            useInspectorStoreHook()
              .getInspectorInfoById({ insId: ruleForm.username })
              .then(resInfo => {
                if (resInfo.code === 200) {
                  router.push("/welcome").then(() => {
                    initRouter();
                    message("登录成功！", { type: "success" });
                  });
                } else {
                  message(resInfo.message, { type: "info" });
                }
              });
          } else {
            console.log("登录失败");
            message(res, { type: "warning" });
          }
        })
        .finally(() => (loading.value = false));
    }
  });
};

const logining = async (insId0: number, insPassword0: string) => {
  loading.value = true;
  useInspectorStoreHook()
    .loginByInsIdByPass({
      insId: insId0,
      insPassword: insPassword0
    })
    .then(res => {
      useInspectorStoreHook()
        .getInspectorInfoById({ insId: insId0 })
        .then(resInfo => {
          router.push("/welcome").then(() => {
            initRouter();
          });
        });
    })
    .finally(() => (loading.value = false));
};

const onUpdate = async (formEl: FormInstance | undefined) => {
  loading.value = true;
  console.log("开始注册");
  if (!formEl) return;
  await formEl.validate(valid => {
    if (valid) {
      if (checked.value) {
        try {
          register({
            insId: ruleFormRegister.insId,
            insName: ruleFormRegister.insName,
            insPassword: ruleFormRegister.registerPassword,
            insTel: ruleFormRegister.insTel,
            insState: ruleFormRegister.insState,
            insAddress: ruleFormRegister.insAddress
          }).then(res => {
            if (res.code === 200) {
              message("注册成功", {
                type: "success"
              });
              logining(
                ruleFormRegister.insId,
                ruleFormRegister.registerPassword
              );
            } else if (res.code === 500) {
              message("网格员编码已存在", {
                type: "warning"
              });
            } else {
              message("注册失败", {
                type: "error"
              });
            }
          });
        } catch (error) {
          console.log(error);
          message("注册失败", {
            type: "error"
          });
        }
        loading.value = false;
      } else {
        loading.value = false;
        message("请勾选隐私政策", {
          type: "warning"
        });
      }
      loading.value = false;
    } else {
      loading.value = false;
    }
  });
};

/** 使用公共函数，避免`removeEventListener`失效 */
function onkeypress({ code }: KeyboardEvent) {
  if (code === "Enter") {
    onLogin(ruleFormRef.value);
  }
}
function onBack() {
  currentPage.value = 0;
}
onMounted(() => {
  window.document.addEventListener("keypress", onkeypress);
});

onBeforeUnmount(() => {
  window.document.removeEventListener("keypress", onkeypress);
});
</script>

<template>
  <div class="select-none">
    <div class="login-container">
      <div class="img">
        <img :src="bg" />
      </div>
      <div class="login-box">
        <div class="login-form">
          <Motion><avatar class="avatar" /></Motion>
          <Motion>
            <h2 class="outline-none">
              <TypeIt
                :options="{ strings: [title], cursor: false, speed: 100 }"
              />
            </h2>
          </Motion>

          <el-form
            v-if="currentPage === 0"
            ref="ruleFormRef"
            :model="ruleForm"
            :rules="loginRules"
            size="large"
          >
            <Motion :delay="100">
              <el-form-item
                :rules="[
                  {
                    required: true,
                    message: '请输入账号',
                    trigger: 'blur'
                  }
                ]"
                prop="username"
              >
                <el-input
                  v-model="ruleForm.username"
                  clearable
                  placeholder="账号"
                  :prefix-icon="useRenderIcon(User)"
                />
              </el-form-item>
            </Motion>

            <Motion :delay="150">
              <el-form-item prop="password">
                <el-input
                  v-model="ruleForm.password"
                  clearable
                  show-password
                  placeholder="密码"
                  :prefix-icon="useRenderIcon(Lock)"
                />
              </el-form-item>
            </Motion>

            <Motion :delay="250">
              <el-button
                class="w-full mt-4"
                size="default"
                type="primary"
                :loading="loading"
                @click="onLogin(ruleFormRef)"
              >
                登录
              </el-button>
            </Motion>

            <Motion :delay="250">
              <el-button
                class="w-full mt-3"
                size="default"
                type="primary"
                plain
                :loading="loading"
                @click="currentPage = 1"
              >
                注册
              </el-button>
            </Motion>
          </el-form>
          <el-form
            v-if="currentPage === 1"
            ref="ruleFormRegisterRef"
            :model="ruleFormRegister"
            size="large"
          >
            <Motion>
              <el-form-item
                :rules="[
                  {
                    required: true,
                    message: '请输入网格员编码',
                    trigger: 'blur'
                  }
                ]"
                prop="insId"
              >
                <el-input
                  v-model="ruleFormRegister.insId"
                  clearable
                  placeholder="网格员编码"
                  :prefix-icon="useRenderIcon(User)"
                />
              </el-form-item>
            </Motion>

            <Motion>
              <el-form-item
                :rules="[
                  {
                    required: true,
                    message: '请输入您的姓名'
                  }
                ]"
                prop="insName"
              >
                <el-input
                  v-model="ruleFormRegister.insName"
                  clearable
                  placeholder="姓名"
                  :prefix-icon="useRenderIcon(User)"
                />
              </el-form-item>
            </Motion>

            <Motion>
              <el-form-item
                :rules="[
                  {
                    required: true,
                    message: '请输入您的电话号码'
                  }
                ]"
                prop="insTel"
              >
                <el-input
                  v-model="ruleFormRegister.insTel"
                  clearable
                  placeholder="电话号码"
                  :prefix-icon="useRenderIcon(User)"
                />
              </el-form-item>
            </Motion>
            <Motion>
              <el-form-item
                :rules="[
                  {
                    required: true,
                    message: '请输入您的地址',
                    trigger: 'blur'
                  }
                ]"
                prop="insAddress"
              >
                <el-input
                  v-model="ruleFormRegister.insAddress"
                  clearable
                  placeholder="详细地址"
                  :prefix-icon="useRenderIcon(User)"
                />
              </el-form-item>
            </Motion>

            <Motion :delay="200">
              <el-form-item prop="registerPassword">
                <el-input
                  v-model="ruleFormRegister.registerPassword"
                  clearable
                  show-password
                  placeholder="密码"
                  :prefix-icon="useRenderIcon(Lock)"
                />
              </el-form-item>
            </Motion>

            <Motion :delay="250">
              <el-form-item :rules="repeatPasswordRule" prop="repeatPassword">
                <el-input
                  v-model="ruleFormRegister.repeatPassword"
                  clearable
                  show-password
                  placeholder="确认密码"
                  :prefix-icon="useRenderIcon(Lock)"
                />
              </el-form-item>
            </Motion>

            <Motion :delay="300">
              <el-form-item>
                <el-checkbox v-model="checked">
                  {{ "我已阅读并接受" }}
                </el-checkbox>
                <el-button link type="primary">
                  {{ "隐私政策" }}
                </el-button>
              </el-form-item>
            </Motion>

            <Motion :delay="350">
              <el-form-item>
                <el-button
                  class="w-full"
                  size="default"
                  type="primary"
                  :loading="loading"
                  @click="onUpdate(ruleFormRegisterRef)"
                >
                  {{ "确定" }}
                </el-button>
              </el-form-item>
            </Motion>

            <Motion :delay="400">
              <el-form-item>
                <el-button class="w-full" size="default" @click="onBack">
                  {{ "返回" }}
                </el-button>
              </el-form-item>
            </Motion>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
@import url("@/style/login.css");
</style>

<style lang="scss" scoped>
:deep(.el-input-group__append, .el-input-group__prepend) {
  padding: 0;
}
</style>
